package com.example.demo.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 表示是否需要重写
     * 返回true则执行beforeBodyWrite方法，反之则不执行
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("code",200);// 状态码
        hashMap.put("msg","");// 错误的描述信息
        hashMap.put("date",body);
        if (body instanceof String){
            // 判断数据类型是不是 String，是String需要特殊处理，因为 String 在转换的时候会报错
            try {
                return objectMapper.writeValueAsString(hashMap);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }
}
